package com.burgeon.backend.college.client_side.service.Impl;

import com.burgeon.backend.EnterpriseWeChat.service.ex.ErrorDataException;
import com.burgeon.backend.SHOP.service.util.MathUtil;
import com.burgeon.backend.college.client_side.entity.*;
import com.burgeon.backend.college.client_side.mappers.AppCollegeMapper;
import com.burgeon.backend.college.client_side.rest.FindEmpNameById;
import com.burgeon.backend.college.client_side.service.AppCollegeService;
import com.burgeon.backend.entity.Info;
import com.burgeon.backend.mappers.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class AppCollegeServiceImpl implements AppCollegeService {

    @Autowired
    private AppCollegeMapper appCollegeMapper;
    @Autowired
    private AccountMapper accountMapper;

    @Override
    public void applyAfterTest(String exam_id, String emp_id) {
        appCollegeMapper.applyAfterTest(exam_id, emp_id);
    }

    @Override
    public HashMap getCourseware(String id, Integer start) {

        CourseOS course = appCollegeMapper.getCourseById(id);

        List<String> coursewares = appCollegeMapper.getCourseware(id, start * 10);
        Integer count = appCollegeMapper.getCoursewareCount(id);


        HashMap data = new HashMap();


        data.put("img", coursewares);

        data.put("count", count);
        data.put("type", course.getType());
        data.put("video", course.getVideo());

        return data;
    }

    @Override
    public HashMap getExamResultData(String exam_id, String empId) throws ErrorDataException {

        System.err.println(exam_id);
        System.err.println(empId);
        ExamRecord examRecord = appCollegeMapper.findExamRecord(exam_id, empId);
        if (examRecord == null) {
            throw new ErrorDataException("成绩不存在");
        }

        Exam examData = appCollegeMapper.getExamData(exam_id);
        int count = appCollegeMapper.findExamItemCount(exam_id);
        CourseOS course = appCollegeMapper.getCourseById(examData.getCourseId());

        HashMap data = new HashMap();


        data.put("examCount", count);
        data.put("title", course.getTitle());
        data.put("score", examRecord.getScore());
        data.put("correct", examRecord.getCorrect());
        data.put("mistake", count - examRecord.getCorrect());
        data.put("accuracy", examRecord.getScore());
        data.put("when", examRecord.getExamTime());
        data.put("fullMark", 100);


        return data;
    }

    @Override
    public void examResult(String exam_id, String empId, Integer examScore,
                           Integer correct, String time, Integer count,
                           String token,String storeId) {

        System.err.println("exam_id=" + exam_id + ",empId=" + empId + ",examScore=" + examScore +
                ",correct=" + correct + ",time=" + time + ",count=" + count + ",token=" + token);

        //查询考题总分
        Integer scoreCount = appCollegeMapper.findExamTotalPoints(exam_id);
        BigDecimal score = MathUtil.divide(new BigDecimal(examScore), new BigDecimal(scoreCount), 2);

        score = MathUtil.multiply(score, new BigDecimal(100), 0);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //若复考改变状态
        //  appCollegeMapper.upExamRecordApply(exam_id,empId);
        Info info = GetInfoByToken(token);
        FindEmpNameById findEmpNameById = new FindEmpNameById(info.getUrl(), info.getAccount(), info.getPassword());
        String empName = findEmpNameById.getData(empId);
        appCollegeMapper.examResult(empName,exam_id, empId, score.intValue(),
                sdf.format(new Date()), token, time, correct,storeId);

    }

    @Override
    public Exam startExam(String course_id) {
        ArrayList<String> arr = new ArrayList<>();
        arr.add("A");
        arr.add("B");
        arr.add("C");
        arr.add("D");
        //查考题
        List<Exam> data = appCollegeMapper.fingExamData(course_id);
        for (Exam exam : data) {
            for (ExamItem examItem : exam.getExamItems()) {
                for (int i = 0; i < examItem.getOptions().size(); i++) {
                    examItem.getOptions().get(i).setAttribute(arr.get(i));
                }
            }
        }

        return data.size() > 0 ? data.get(0) : null;
    }
    private Info GetInfoByToken(String token) {
        return accountMapper.GetTokenData(token);
    }
    @Override
    public HashMap recordLearning(String course_id, String empId, String token) {
        System.err.println("course_id=" + course_id + ",empId=" + empId + ",token=" + token);
        HashMap data = new HashMap();
        CourseRecord courseRecord = appCollegeMapper.findCourseRecord(course_id, empId);

        appCollegeMapper.UpCourseRecord(courseRecord.getId());

        CourseOS course = appCollegeMapper.getCourseById(course_id);
        System.err.println(course.getStudy() + "xxx" + courseRecord.getLearningTime());
        System.err.println(courseRecord);
        if (course.getStudy() == (courseRecord.getLearningTime() + 1)) {
            data.put("result", "finish");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            appCollegeMapper.UpCourseRecordState(courseRecord.getId(), sdf.format(new Date()));
        } else {
            data.put("result", "unfinished");
        }

        return data;
    }

    public static void main(String[] args) {
        int i = MathUtil.multiply(
                MathUtil.divide(
                        new BigDecimal(4),//yi
                        new BigDecimal(6),//zong
                        2

                ), new BigDecimal(100), 0).intValue();
        System.err.println(i);
    }

    @Override
    public HashMap getCourseList(String empId, String token) {

        HashMap data = new HashMap();
        List<CourseOS> studying = new ArrayList<CourseOS>();
        data.put("hint", null);

        System.err.println(empId + "--" + token);

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        SimpleDateFormat ssdf = new SimpleDateFormat("yyyy.MM.dd");

        List<CourseOS> CourseOSs = appCollegeMapper.getCourseList(token);


        for (CourseOS courseOS : CourseOSs) {
            courseOS.setLearned(0);//初始化已学习时间
            //判断 学习记录 学习进度 考试数据 考试记录 课程时间
            //未学习 学习中 考试暂停 待考试 已完成 已过期
            CourseRecord courseRecord = appCollegeMapper.findCourseRecord(courseOS.getId(), empId);
            DisplayType state = DisplayType.未学习;


            if (null != courseRecord) { //学习记录不为空 已学习
                state = DisplayType.学习中;
                //学习进度%
                courseOS.setSchedule(
                        MathUtil.multiply(
                                MathUtil.divide(
                                        new BigDecimal(courseRecord.getLearningTime()),
                                        new BigDecimal(courseOS.getStudy()),
                                        2

                                ), new BigDecimal(100), 0).intValue()

                );

                courseOS.setLearned(courseRecord.getLearningTime());
                state = curricularJudgmentPrescription(date, sdf, courseOS, state);


                if ("Y".equals(courseRecord.getState())) { //学习已完成
                    Exam examData = appCollegeMapper.findExamData(courseOS.getId());


                    if (null != examData) { //考试不为空

                        state = DisplayType.开始考试;

                        try {
                            //判断时间
                            Date endTime = sdf.parse(examData.getEndTime());
                            Date startTime = sdf.parse(examData.getStartTime());
                            if (date.getTime() > endTime.getTime()) {
                                state = DisplayType.缺考;
                            } else if (date.getTime() < startTime.getTime()) {
                                state = DisplayType.未开始;
                            } else {
                                String hint = calculateTimeDifferenceByCalendar(courseOS.getTitle(), endTime);
                                data.put("hint", hint);
                            }


                        } catch (ParseException e) {
                            e.printStackTrace();
                            state = DisplayType.无;
                        }

                        //考试完成 查看结果
                        ExamRecord examRecord = appCollegeMapper.findExamRecord(examData.getId(), empId);
                        if (null != examRecord) {
                            state = DisplayType.查看考试结果;
                            data.put("hint", null);

                            if ("S".equals(examRecord.getApply())) {
                                state = DisplayType.开始复考;

                            }
                        }


                    } else {
                        state = DisplayType.考试暂停;

                    }


                }

            } else {
                state = curricularJudgmentPrescription(date, sdf, courseOS, state);
            }


            courseOS.setState(state.toString());
            if (DisplayType.学习中.equals(state)) {

                try {
                    String endTimeHint = calculateTimeDifferenceByCalendar(sdf.parse(courseOS.getEndTime()));
                    courseOS.setCourseEndTimeStr(endTimeHint);//课程结束时间
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                studying.add(courseOS);
            }

            try {
                courseOS.setStartTime(ssdf.format(sdf.parse(courseOS.getStartTime())));
                courseOS.setEndTime(ssdf.format(sdf.parse(courseOS.getEndTime())));
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }
        data.put("studying", studying);
        data.put("all", CourseOSs);


        return data;
    }

    private DisplayType curricularJudgmentPrescription(Date date, SimpleDateFormat sdf, CourseOS courseOS, DisplayType state) {
        try {
            Date endDate = sdf.parse(courseOS.getEndTime());
            if (date.getTime() > endDate.getTime()) {
                state = DisplayType.已结束;
//                        if ("N".equals(courseRecord.getState())) {
//                            state = DisplayType.缺考;
//                        }
            }
            Date startDate = sdf.parse(courseOS.getStartTime());
            if (date.getTime() < startDate.getTime()) {
                state = DisplayType.未开始;
            }
        } catch (ParseException e) {
            e.printStackTrace();
            state = DisplayType.无;
        }
        return state;
    }

    @Override
    public String startCourse(String id, String empid, String token,String storeId) throws ErrorDataException {

        CourseRecord record = appCollegeMapper.findCourseRecord(id, empid);
        if (null != record) {
            throw new ErrorDataException("已参加考试");
        }

        CourseRecord courseRecord = new CourseRecord();
        courseRecord.setEmpid(empid);
        courseRecord.setCourse_id(id);
        courseRecord.setToken(token);
        courseRecord.setLearningTime(0);
        courseRecord.setStoreId(storeId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime = sdf.format(new Date());
        courseRecord.setStartTime(nowTime);

        appCollegeMapper.createCourseRecord(courseRecord);

        //添加课程人数
        appCollegeMapper.addCourseCount(id);

        return courseRecord.getId();
    }

    enum DisplayType {
        未学习, 学习中, 已结束, 缺考, 未开始, 开始考试, 考试暂停, 查看考试结果, 无, 开始复考

    }

    private String calculateTimeDifferenceByCalendar(String collegeName, Date date) {


        Calendar c1 = Calendar.getInstance();   //当前日期
        Calendar c2 = Calendar.getInstance();
        c2.setTime(date);   //设置为另一个时间

        int HOUR = c1.get(Calendar.HOUR);
        int oldHOUR = c2.get(Calendar.HOUR);

        int DAY = c1.get(Calendar.DAY_OF_YEAR);
        int oldDAY = c2.get(Calendar.DAY_OF_YEAR);


        int sH = oldHOUR-HOUR;
        int sD = oldDAY-DAY;

        if (sH<0){
            sH+=24;
            sD-=1;
            if (sD<0){
                sD=0;
            }
        }

        return collegeName + "-考试结束还有" +
                (sD > 0 ? sD + "天" : "")
                + sH + "小时结束!请抓紧时间就考";
    }

    private String calculateTimeDifferenceByCalendar( Date date) {


        Calendar c1 = Calendar.getInstance();   //当前日期
        Calendar c2 = Calendar.getInstance();
        c2.setTime(date);   //设置为另一个时间

        int minute = c1.get(Calendar.MINUTE);
        int endMinute = c2.get(Calendar.MINUTE);

        int HOUR = c1.get(Calendar.HOUR);
        int endHOUR = c2.get(Calendar.HOUR);

        int DAY = c1.get(Calendar.DAY_OF_YEAR);
        int endDAY = c2.get(Calendar.DAY_OF_YEAR);

        int sM = endMinute-minute;
        int sH = endHOUR -HOUR;
        int sD = endDAY - DAY;


        if (sM<0){
            sM+=60;
            sH -=1;
            if (sH<0){
                sH+=24;
                sD-=1;
                if (sD<0){
                    sD=0;
                }
            }
        }


        return "距离课程结束时间还有:"+
                (sD > 0 ? sD + "天" : "")
                + sH + "小时"+sM+"分钟结束";
    }


}
